//
//  ST_SVGAGiftPlayController.swift
//  btvideo
//
//  Created by mac on 2021/5/7.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SVGAPlayer
import RxCocoa
import RxSwift


class ST_SVGAGiftPlayController: UIViewController {
    
    deinit {
        print("SVGA play bug ---deinit")
    }
    
    var disposeBag = DisposeBag()

    let loading = ST_ActivityIndicator()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(player)
        player.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(self.loadingLabel)
        self.loadingLabel.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        binding()
        
    }
    
    fileprivate func binding(){
        
        loadingLabel.alpha = 1
        
        ST_GiftAssetProvider.playSVGASession(urlString: svgaUrl?.absoluteString).withUnretained(self).subscribe { own , entity in
        
            own.loadingLabel.alpha = 0
            
            own.player.videoItem = entity
            
            own.player.startAnimation()
            
        } onError: {[weak self] e in
            
            self?.goback_previous_controller()
            
        }.disposed(by: disposeBag)
        
    }
    
    var svgaUrl:URL?
    
    
    var dismissClosure:(()->())?
    
    fileprivate lazy var player:SVGAPlayer = {
        
        let p  = SVGAPlayer()
        p.delegate = self
        p.loops = 1
        return p
    }()
    
    
    fileprivate lazy var loadingLabel:UILabel = {
       let control = UILabel()
        control.text = "特效加载中..."
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        control.textColor = .white
        control.alpha = 0
        return control
    }()
    
    /*
    fileprivate lazy var scan_animate_view:LOTAnimationView = {
        
        let path = Bundle.main.path(forResource: "receiveGiftBack", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        
        control.loopAnimation = true
        
        return control
    }()

    */
}


extension ST_SVGAGiftPlayController:SVGAPlayerDelegate{
    
    
    func svgaPlayerDidFinishedAnimation(_ player: SVGAPlayer!) {
        
        self.goback_previous_controller(animated: false) {
            self.dismissClosure?()
        }
    }
    
}
